using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace FrameWork.Inventory
{
    /// <summary>
    /// 操作UI界面
    /// 按钮事件
    /// 管理UI界面初始化
    /// UI界面数据更新
    /// </summary>
    public class InventoryViewController : BasePanel
    {
        [Header("UI界面按钮")]
        [SerializeField]private Button itemOrdering; // 物品排序
        [SerializeField] private Button closePanel;  // 关闭页面

        [Header("库存SO文件")] [SerializeField] private InventorySO myInventory;

        [Header("UI界面")] [SerializeField] private InventoryView view;
        
        public int MaxSize { get; private set; } = 20;

        private void Awake()
        {
            // UI界面初始化
            view.FillItemToUI(MaxSize);

            // 注册事件，UI界面更新
            myInventory.OnInventoryUpdate += UpdateInventoryUI;

            // 按钮事件注册
            itemOrdering.onClick.AddListener(() =>
            {
                myInventory.ItemOrdering();
            });
            closePanel.onClick.AddListener(() =>
            {
                //
            });
        }
        
        private void OnEnable()
        {
            // 每次打开页面就重新初始化页面
            // view.FillItemToUI(MaxSize);
            // myInventory.OnInventoryUpdate += UpdateInventoryUI;
            myInventory.UpdateView();
        }

        private void Start()
        {
            closePanel.onClick.AddListener(() =>
            {
                UIManager.Instance.ClosePanel(UIConst.INVENTORY);
            });
        }

        private void OnDisable()
        {
            myInventory.OnInventoryUpdate -= UpdateInventoryUI;
        }

        // 界面更新
        private void UpdateInventoryUI(Dictionary<int, InventoryItem> inventoryState)
        {
            // 重置所有格子
            view.ResetAllItems();

            // 更新格子信息
            foreach (var item in inventoryState)
            {
                view.UpdateViewInfo(item.Key, item.Value);
            }
        }
    }
}
